package com.example.onion.hxchat.fragment;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.example.onion.hxchat.activity.FriendApplyNotificationActivity;
import com.example.onion.hxchat.activity.ScanUserActivity;
import com.example.onion.hxchat.adapter.MyFriendAdapter;
import com.example.databean.FriendBean;
import com.example.onion.hxchat.mvvm.InfoViewModel;
import com.example.onion.hxchat.mvvm.WcFriendViewModel;
import com.example.onion.hxchat.room.entity.Friend;
import com.example.onion.hxchat.room.entity.Info;
import com.example.onion.hxchat.util.MyLocalDatabaseHelper;
import com.example.onion.hxchat.util.PassWordHelp;
import com.example.superyi.myteam.R;

import java.util.ArrayList;
import java.util.List;

/**
 * 显示当前用户的好友列表的fragment
 * 含version
 */
public class FriendFragment extends Fragment {

    private int version = 4;

    private MyLocalDatabaseHelper deHelper;
    private View view;  //定义view用来设置fragment的layout
    public RecyclerView mRecyclerView;  //定义RecyclerView
    //定义以goodsentity实体类为对象的数据集合

    private TextView friendApplyTv;
    private List<FriendBean> mList = new ArrayList<>();
    //自定义recyclerveiw的适配器
    private MyFriendAdapter myFriendAdapter;

    private WcFriendViewModel friendViewModel;
    private String accountId;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_friend, container, false);
        deHelper = new MyLocalDatabaseHelper(getContext(),"local.db",null,version);
        initRecyclerView();
        accountId = PassWordHelp.readPassword(requireContext())[0];
        initData();
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        friendViewModel = new ViewModelProvider(requireActivity()).get(WcFriendViewModel.class);
        friendViewModel.getOwnFriends(accountId).observe(requireActivity(), new Observer<List<Friend>>() {
            @Override
            public void onChanged(List<Friend> friends) {
                myFriendAdapter.setmList(friends);
                myFriendAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private void initData() {


//        SQLiteDatabase db = deHelper.getWritableDatabase();
//        Cursor cursor = db.rawQuery("select * from friend",null);
//
//        //这里做判断，本地无一好友信息  应该请求服务器
//        if (cursor.moveToFirst()){
//            do {
//                String userId = cursor.getString(cursor.getColumnIndex("userId"));
//                String userName = cursor.getString(cursor.getColumnIndex("userName"));
//                FriendBean friendBean = new FriendBean(userName,userId);
//                mList.add(friendBean);
//            }while (cursor.moveToNext());
//        }
//        for (int i = 0; i < 5; i++) {
//            FriendBean friendBean = new FriendBean();
//            friendBean.setUserName("好友页面的第" + (i + 1) + "個名字1234");
//            friendBean.setInfo("第" + (i + 6) + "個介紹1234");
//            friendBean.setUserId("1234");
//            mList.add(friendBean);
//        }
    }

    /**
     * TODO 对recycleview进行配置
     */

    private void initRecyclerView() {
        friendApplyTv = view.findViewById(R.id.friend_fragment_apply_wc);
        friendApplyTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getContext(), FriendApplyNotificationActivity.class));
            }
        });


                //获取RecyclerView
        mRecyclerView = view.findViewById(R.id.friend_fragment_recyclerview_wc);
        //创建adapter
        myFriendAdapter = new MyFriendAdapter();
        //适配器只负责得到数据吧，跳转页面由从适配器获取到数据的Activity或者Fragment（本fragment页面）去选择跳转到哪个页面
        myFriendAdapter.setDataGetterListener(new MyFriendAdapter.DataGetterListener() {
            @Override
            public void getItemData(Friend friendBean) {//friendBean通过回调机制从适配器中得到的friendBean数据
                Toast.makeText(getContext(), "名字是：" + friendBean.getUserName()+"id"+friendBean.getUserId(), Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getContext(), ScanUserActivity.class);
                intent.putExtra("scanUserName", friendBean.getUserName());//传递用户名称至用户浏览信息(加scan前缀)页面显示
                intent.putExtra("scanUserId", friendBean.getUserId());//传递用户id至用户浏览信息页面显示
                startActivity(intent);
            }

        });
        //给RecyclerView设置adapter
        mRecyclerView.setAdapter(myFriendAdapter);
        //设置layoutManager,可以设置显示效果，是线性布局、grid布局，还是瀑布流布局
        //参数是：上下文、列表方向（横向还是纵向）、是否倒叙
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        //设置item的分割线
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        //RecyclerView中没有item的监听事件，需要自己在适配器中写一个监听事件的接口。参数根据自定义
//        myFriendAdapter.setOnItemClickListener(new CollectRecycleAdapter.OnItemClickListener() {
//            @Override
//            public void OnItemClick(View view, GoodsEntity data) {
//                //此处进行监听事件的业务处理
//                Toast.makeText(getActivity(),"我是item",Toast.LENGTH_SHORT).show();
//            }
//        });
    }

}
